package com.EthanYankang;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Ethan Yankang
 * @Program: diy-tomcat
 * @Date: 2024-09-08 09:40
 **/
public class Response extends AbstructHttpServletResponse{
    private Request request;//一个请求对应一个响应吗，，嘛
    private OutputStream socketOutputStream;//发送的响应的目的地，向套接字流里面写去
    private int status=200;
    private String message="OK";
    private Map<String,String> header=new HashMap<>();
    private ResponseServletGetOutputStream responseServletGetOutputStream=new ResponseServletGetOutputStream();//该响应的响应体

    //响应的格式
    private final static byte SP=' ';
    private final static byte  CR='\r';
    private final static byte LF='\n';

    public Response(Request request) throws IOException {
        this.request = request;
        this.socketOutputStream=request.getSocket().getOutputStream();
    }

    //tomcat中真正发送响应的方法
    public void complete() throws IOException {
        sendResponseLine();//发送响应行
        sendResponseHeader();//发送响应头
        sendResponseBody();//发送响应体

        System.out.println("响应完成");
    }


    private void sendResponseLine() throws IOException {
       socketOutputStream.write(request.getProtocol().getBytes());
       socketOutputStream.write(SP);
       socketOutputStream.write(status);
       socketOutputStream.write(SP);
       socketOutputStream.write(message.getBytes());
       socketOutputStream.write(CR);
       socketOutputStream.write(LF);
    }

    private void sendResponseHeader() throws IOException {
        //发送每一行响应体
        for (Map.Entry<String, String> entry : header.entrySet()) {
            socketOutputStream.write(entry.getKey().getBytes());
            socketOutputStream.write(":".getBytes());
            socketOutputStream.write(entry.getValue().getBytes());
            socketOutputStream.write(CR);
            socketOutputStream.write(LF);
        }
        //响应体发送结束
        socketOutputStream.write(CR);
        socketOutputStream.write(LF);
    }


    private void sendResponseBody() throws IOException {
            //这就是我们自己的响应
            socketOutputStream.write(this.getOutputStream().getBytes());
    }


    @Override
    public void setStatus(int i, String s) {
        status=i;
        message=s;
    }

    @Override
    public int getStatus() {
        return status;
    }

    @Override
    public void setStatus(int i) {
        status=i;
    }
//是向浏览器写入字节，返回响应的方法
    @Override
    public ResponseServletGetOutputStream getOutputStream() throws IOException {
        return responseServletGetOutputStream;
    }

    @Override
    public void addHeader(String s, String s1) {
        //前面的手动添加的响应头方法会自动被写入！！
        header.put(s,s1);
    }
}
